﻿#include "LuaRef.h"
#include "LuaState.h"

#define INVALID_REF (-1)

LuaRef::LuaRef() 
	:m_ls(nullptr), m_ref(INVALID_REF)
{
}

LuaRef::LuaRef(LuaObject obj) 
	:m_ls(nullptr),m_ref(INVALID_REF)
{
	ref(obj);
}

LuaRef::LuaRef(LuaRef&& ref) 
	:m_ls(ref.m_ls), m_ref(ref.m_ref)
{
	ref.m_ls = nullptr;
	ref.m_ref = INVALID_REF;
}

LuaRef::~LuaRef() {
	unref();
}

LuaRef& LuaRef::operator=(const LuaObject& obj) {
	unref();//取消引用
	ref(obj);//添加引用
	return *this;
}

LuaObject LuaRef::getObject() {
	if (m_ls) {
		return m_ls->getRef(m_ref);
	} else {
		return luaNil;
	}
}

LuaObject LuaRef::getObject(LuaState* L) {
	if (m_ls) {
		return L->getRef(m_ref);
	} else {
		return luaNil;
	}
}

void LuaRef::ref(const LuaObject& obj) {
	LuaState* L = obj.getCppLuaState();
	if (L) {
		m_ls = L->owner();
		m_ref = L->ref(obj);
	}
}

void LuaRef::unref() {
	if (m_ls) {
		m_ls->unref(m_ref);
		m_ref = INVALID_REF;
		m_ls = nullptr;
	}
}





